import React, { useState } from 'react'
import { Modal, Form, Input, Select, message } from 'antd'
import { useRequest, useMount } from 'ahooks'
import { listCommunicationChains, createApplication, listApplications } from '@/pages/Dashboard/components/CrossChain/service'

import './New.less'

const NewCrossChainApplication = ({ visible, onCancel, chain = {}, contracts = [], onSuccess, listenedContractFunc = {}}) => {
  const [form] = Form.useForm()
  const [communicationChains, setCommunicationChains] = useState([])
  const { loading: loadingCommunicationChains, run: loadCommunicationChains } = useRequest(listCommunicationChains, { manual: true })
  const { loading: creating, run: newApplication } = useRequest(createApplication, { manual: true })
  const [appliedContracts, setAppliedContracts] = useState([])
  const { loading: loadingApplications, run: loadApplications } = useRequest(listApplications, { manual: true })
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  }
  const { id: chainId, name: chainName } = chain
  const onOk = async() => {
    const values = await form.validateFields()
    const res = await newApplication({
      ...values,
      sender: chainId,
      sponsor: chainId,
    })
    const { data: { success }} = res
    if (success) {
      message.success('创建跨链申请成功')
      form.resetFields()
      onSuccess()
    }
  }
  const initialValues = {
    role: 'source',
  }
  const fetchCommunicationChains = async(params) => {
    try {
      const res = await loadCommunicationChains(params)
      const { data: { data }} = res
      const chains = data.filter((item) => item.id !== chainId)
      setCommunicationChains(chains)
    } catch (e) {
      console.error(e)
    }
  }
  const onChangeTarget = async(value) => {
    const res = await loadApplications({
      source: chainId,
      target: value,
    })
    const { data: { data: applications = [] }} = res
    const contractIds = applications.map((application) => application.contract_id)
    setAppliedContracts(contractIds)
  }
  // const onChangeChannel = (value) => {
  //   fetchCommunicationChains({
  //     per_page: -1,
  //     channel_id: value,
  //   })
  // }
  useMount(() => {
    fetchCommunicationChains({
      per_page: -1,
      status: 2,
    })
  })
  const validateSourceListenFunc = (_, value) => {
    const listenContract = form.getFieldValue('listenContract') || ''
    const funcs = listenedContractFunc[listenContract] || []
    if (funcs.indexOf(value) >= 0) {
      return Promise.reject('此合约方法已被监听')
    }
    return Promise.resolve()
  }

  return (
    <Modal
      visible={visible}
      confirmLoading={creating}
      title="申请跨链通讯"
      okText="确认"
      cancelText="取消"
      width={650}
      onCancel={() => {
        form.resetFields()
        onCancel()
      }}
      onOk={onOk}>
      <Form
        {...layout}
        form={form}
        initialValues={initialValues}
      >
        <Form.Item
          label="来源链"
        >
          <span className="ant-form-text">{chainName}</span>
        </Form.Item>
        <Form.Item
          label="目标链"
          name="receiver"
          rules={[{ required: true, message: '请选择目标链' }]}
        >
          <Select placeholder="请选择目标链" loading={loadingCommunicationChains} onChange={onChangeTarget}>
            {communicationChains.map((chain) => <Select.Option disabled={chain.id === chainId} key={chain.id} value={chain.id}>{chain.name}</Select.Option>)}
          </Select>
        </Form.Item>
        <Form.Item
          label="跨链合约名称"
          name="contractId"
          rules={[{ required: true, message: '请选择跨链合约名称' }]}
        >
          <Select placeholder="请选择跨链合约名称" loading={loadingApplications}>
            {contracts.map((contract) => <Select.Option key={contract.id} value={contract.id}>{contract.name}</Select.Option>)}
          </Select>
        </Form.Item>
        <Form.Item
          label="监听来源合约"
          name="listenContract"
          rules={[{ required: true, message: '请输入监听来源合约' }]}
        >
          <Input placeholder="请输入监听来源合约" />
        </Form.Item>
        <Form.Item
          label="监听来源链合约方法"
          name="listenMethod"
          rules={[
            { required: true, message: '请输入监听来源链合约方法' },
            {
              validator: validateSourceListenFunc,
            },
          ]}
        >
          <Input placeholder="请输入监听来源链合约方法" />
        </Form.Item>
        <Form.Item
          label="目标链合约"
          name="toContract"
          rules={[{ required: true, message: '请输入目标链合约' }]}
        >
          <Input placeholder="请输入目标链合约" />
        </Form.Item>
        <Form.Item
          label="目标链合约方法"
          name="toMethod"
          rules={[{ required: true, message: '请输入监听目标链合约方法' }]}
        >
          <Input placeholder="请输入监听目标链合约方法" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default NewCrossChainApplication
